package com.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;


/**
 * ClassName: JwtInterceptor
 * Description:
 *
 * @author L_Z_R
 * @version 1.0
 * @create 2025/05/28 19:56
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 处理 OPTIONS 请求，直接放行
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }


        // 从请求头中获取JWT令牌
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("缺少token令牌,或者token格式错误");
            return false;
        }

        try {
            // 验证JWT令牌并提取用户ID
            String authHeader = token.substring(7); //  移除"Bearer "前缀
            Claims claims = JwtUtils.parseToken(authHeader);
            String userId = claims.getSubject(); // 获取用户ID

            // 将用户ID存储到请求的上下文中
            request.setAttribute("userId", userId);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("token令牌无效");
            return false;
        }

        return true;
    }
}
